﻿using System.Configuration;
using MongoDB.Driver;

namespace Mockingbird.MVC.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Web;
    using System.Web.Mvc;

    using Core.Infrastructure.Logging.Interfaces;
    using Core.Models;
    using Core.Repository;
    using Infrastructure.BaseTypes;
    using MongoDB.Bson;

    public class NewsFeedController : BaseController
    {
        private INewsFeedRepository newsFeedRepository;
        private IAccountRepository accountRepository;

        public NewsFeedController(ILogger logger, INewsFeedRepository newsFeedRepository, IAccountRepository accountRepository)
            : base(logger)
        {
            this.newsFeedRepository = newsFeedRepository;
            this.accountRepository = accountRepository;
        }

        public ActionResult Index()
        {
            var feed = newsFeedRepository.GetMyNewsFeed(User.Properties.Id);

            Session["Feed"] = feed;

            ViewBag.UserName = User.Properties.Name;

            return View("_NewsFeed", feed);
        }

        public ActionResult GetHashTags(string searchText)
        {
            var result = newsFeedRepository.GetHashTags(searchText);

            return View("_NewsFeedList", result);
        }

        [OutputCache(Duration = 0)]
        public ActionResult GetNewsFeedForUserHeartbeat()
        {
            var friends = new List<ObjectId>();

            friends.Add(User.Properties.Id);
            friends.AddRange(User.Properties.Friends);

            var list = newsFeedRepository.GetLatestNews(friends);

            Session["Feed"] = list;
            ViewBag.UserName = User.Properties.Name;

            return View("_NewsFeedList", list);
        }

        public ActionResult GetNewsFeedForUser(string userId)
        {
            var user = accountRepository.GetUserById(userId);

            var friends = new List<ObjectId>();

            friends.Add(new ObjectId(userId));
            friends.AddRange(user.Friends);

            var list = newsFeedRepository.GetLatestNews(friends);

            Session["Feed"] = list;
            ViewBag.UserName = user.Name;
            ViewBag.UseHeartbeat = true;

            return View("_NewsFeed", list);
        }

        public ActionResult GetUserFeeds(string userId)
        {
            var user = accountRepository.GetUserById(userId);

            var feed = newsFeedRepository.GetMyNewsFeed(new ObjectId(userId));

            Session["Feed"] = feed;

            ViewBag.UserName = user.Name;

            return View("_NewsFeed", feed);
        }

        [HttpGet]
        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(string text, string location)
        {
            if (text.Length > 140)
            {
                throw new ArgumentException("Max length exceeded!");
            }

            var news = new NewsFeedModel
                        {
                            Date = DateTime.Now,
                            AuthorId = new MongoDBRef(ConfigurationManager.AppSettings["UserTableName"], User.Properties.Id),
                            Text = text,
                            Location = location
                        };

            newsFeedRepository.CreateEvent(news);

            news.Author = User.Properties;

            return View("_NewsFeedListItem", news);
        }

        public ActionResult UploadPhoto(HttpPostedFileBase file)
        {
            using (var ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);

                var news = new NewsFeedModel
                {
                    Date = DateTime.Now,
                    AuthorId = new MongoDBRef(ConfigurationManager.AppSettings["UserTableName"], User.Properties.Id),
                    Image = ms.ToArray(),
                };

                newsFeedRepository.CreateEvent(news);
                
                return RedirectToAction("Index");
            }
        }

        public ActionResult GetImage(string postId)
        {
            var feeds = (List<NewsFeedModel>)Session["Feed"];

            foreach (var feed in feeds)
            {
                if (feed.Id.ToString() == postId && feed.Image != null)
                {
                    return File(feed.Image, "image/*");
                }
            }

            return null;
        }
    }
}
